package com.xiaoyu.merchant.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.techfansy.bottomDialog.BottomDialog;
import com.techfansy.moreImageSelected.BitmapUtils;
import com.techfansy.photo.PhotoSelect;
import com.techfansy.utils.PermissionUtils;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.xiaoyu.commonlib.BillionCardConstants;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivity;
import com.xiaoyu.commonlib.ui.widget.ContainsEmojiEditText;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.merchant.R;
import com.xiaoyu.merchant.model.OpenShopInfoBean;
import com.xiaoyu.merchant.model.PayResult;
import com.xiaoyu.merchant.network.NetworkConstants;
import com.xiaoyu.merchant.network.NetworkManager;
import com.xiaoyu.merchant.ui.activity.login.LoginActivity;
import com.xiaoyu.merchant.ui.dialog.LogOutDialog;
import com.xiaoyu.merchant.ui.dialog.WaitAuditDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static java.lang.System.currentTimeMillis;


/**
 * @author jx
 * @date 创建时间 2019/1/2
 * @Description申请开店
 */
public class ApplyShopActivity extends BaseActivity implements LogOutDialog.ILogOutListener {

    private static final int SDK_PAY_FLAG = 1;
    private String path;
    @BindView(R.id.shop_name)
    ContainsEmojiEditText mShopNameEdit;
    @BindView(R.id.store_about)
    ContainsEmojiEditText mStoreAboutEdit;
    @BindView(R.id.activity_forum_add_content_world_count)
    TextView aboutCountTxt;

    @BindView(R.id.activity_apply_shop_front_img)
    ImageView mFrontImg;//正面
    @BindView(R.id.activity_apply_shop_contrary_img)
    ImageView mContraryImg;//反面
    @BindView(R.id.activity_apply_shop_hand_img)
    ImageView mHandImg;//手持身份证
    @BindView(R.id.activity_apply_shop_selfie_img)
    ImageView mSelfieImg;//自拍照

    @BindView(R.id.apply_shop_address)
    EditText mAddress;
    @BindView(R.id.amount)
    TextView mAmount;

    private int state;
    private String mImgPath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_shop);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        mStoreAboutEdit.addTextChangedListener(onTitleWatcher);
        getOpenShopInfo();
    }

    private void getOpenShopInfo() {
        NetworkManager.openShopInfo(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                successOpenShopInfo(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    private void successOpenShopInfo(String result) {
        OpenShopInfoBean bean = new Gson().fromJson(result, OpenShopInfoBean.class);
        Log.i("jx", "successOpenShopInfo: state==" + state);
        if (!bean.getData().getStorestate().equals("3")) {
            WaitAuditDialog dialog = new WaitAuditDialog(ApplyShopActivity.this, false, false);
            dialog.show();
        }
        mShopNameEdit.setText(bean.getData().getStorename());//店铺名称
        mStoreAboutEdit.setText(bean.getData().getStoreintroduce());//店铺介绍
        Glide.with(this).load(bean.getData().getIdcardfront()).into(mFrontImg);
        Glide.with(this).load(bean.getData().getIdcardback()).into(mContraryImg);
        Glide.with(this).load(bean.getData().getImagefront()).into(mHandImg);
        Glide.with(this).load(bean.getData().getImageback()).into(mSelfieImg);
        mAddress.setText(bean.getData().getStoreaddresss());//地址
//        mAmount.setText("注意：开店需要缴纳"+bean.getData().getAmount()+"元保证金");
    }


    //申请开店
    @OnClick(R.id.apply_open_shop)
    public void applyOpenShopClick() {
        if (TextUtils.isEmpty(mShopNameEdit.getText().toString()) || TextUtils.isEmpty(mStoreAboutEdit.getText().toString()) ||
                TextUtils.isEmpty(mAddress.getText().toString())
                || mFrontImg.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.mipmap.front).getConstantState()
                || mContraryImg.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.mipmap.reverse_side).getConstantState()
                || mHandImg.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.mipmap.hand_id_card).getConstantState()
                || mSelfieImg.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.mipmap.selfie).getConstantState()) {

            ToastUtil.showToast(ApplyShopActivity.this, "请上传相关内容");
            return;
        }
        //调接口上传数据申请开店

        setPayDialog();
    }

    private void getApplyOpenShop() {
        NetworkManager.applyOpenShop(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), mShopNameEdit.getText().toString(),
                mStoreAboutEdit.getText().toString(), mImgPath, mImgPath, mImgPath, mImgPath, mAddress.getText().toString(), new CommonHttpResponser() {
                    @Override
                    public void onSuccess(String result) {

                        WaitAuditDialog dialog = new WaitAuditDialog(ApplyShopActivity.this, false, false);
                        dialog.show();
                    }

                    @Override
                    public void onFailed(String errorCode, String errorDiscription) {

                    }
                });
    }

    //正面
    @OnClick(R.id.activity_apply_shop_front)
    public void frontClick() {
        setPopupPhoto();
        state = 1;
    }

    //反面
    @OnClick(R.id.activity_apply_shop_reverse)
    public void reverseClick() {
        setPopupPhoto();
        state = 2;
    }

    //手持身份证照
    @OnClick(R.id.activity_apply_shop_upload_photo)
    public void handImgClick() {
        setPopupPhoto();
        state = 3;
    }

    //自拍照
    @OnClick(R.id.activity_apply_shop_self_portrait)
    public void selfPortraitClick() {
        setPopupPhoto();
        state = 4;
    }

    private void setPopupPhoto() {
        new BottomDialog(this).addItemSheet(R.string.photo_album_to_choose, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                permissionUtils.setPermissionUtils(ApplyShopActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PhotoSelect.REQUEST_CAMERA, new PermissionUtils.RequestPermissionListener() {
                    @Override
                    public void permission(int i) {
                        new PhotoSelect(ApplyShopActivity.this, true, true);
                    }
                });

            }
        }).addItemSheet(R.string.photo, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                permissionUtils.setPermissionUtils(ApplyShopActivity.this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                }, PhotoSelect.REQUEST_CAMERA, new PermissionUtils.RequestPermissionListener() {
                    @Override
                    public void permission(int i) {
                        new PhotoSelect(ApplyShopActivity.this, false, true);
                    }
                });

            }
        }).setCancel(new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
            }
        }).show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //接收“相册与拍照”获取到的图片
        if (resultCode == PhotoSelect.REQUEST_CAMERA) {
            if (data == null) return;
            try {
                path = data.getExtras().getString("path");
                Bitmap bitmap = BitmapUtils.getBitmap(path, 800, 800);
                switch (state) {
                    case 1:
                        mFrontImg.setImageBitmap(bitmap);
                        uploadOSSUrl(path, currentTimeMillis() + path.substring(path.lastIndexOf("/") + 1));//将图片上传至OSS
                        break;
                    case 2:
                        mContraryImg.setImageBitmap(bitmap);
                        uploadOSSUrl(path, currentTimeMillis() + path.substring(path.lastIndexOf("/") + 1));//将图片上传至OSS
                        break;
                    case 3:
                        mHandImg.setImageBitmap(bitmap);
                        uploadOSSUrl(path, currentTimeMillis() + path.substring(path.lastIndexOf("/") + 1));//将图片上传至OSS
                        break;
                    case 4:
                        mSelfieImg.setImageBitmap(bitmap);
                        uploadOSSUrl(path, currentTimeMillis() + path.substring(path.lastIndexOf("/") + 1));//将图片上传至OSS
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadOSSUrl(String filePath, String objectKey) {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BillionCardConstants.BACKET_NAME, objectKey, filePath);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(BillionCardConstants.ACCESS_KEY_ID, BillionCardConstants.ACCESS_KEY_SECRET);
        try {
            OSSClient oss = new OSSClient(this, BillionCardConstants.ENDPOINT, credentialProvider);
            PutObjectResult putResult = oss.putObject(put);
            mImgPath = "https://yikabangb.oss-cn-beijing.aliyuncs.com/" + objectKey;
        } catch (ClientException e) {
            // 本地异常如网络异常等
            e.printStackTrace();
        } catch (ServiceException e) {
            // 服务异常
        }
    }

    /**
     * 店铺简介编辑框输入监听
     */
    private TextWatcher onTitleWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String count = s.length() + "/100";
            aboutCountTxt.setText(count);
        }
    };


    //退出登录
    @OnClick(R.id.log_out)
    public void logOutClick() {
        LogOutDialog dialog = new LogOutDialog(this);
        dialog.setILogOut(this);
        dialog.show();
    }

    @Override
    public void OnLogOut() {
        //退出到登录页面
        if (PreferencesUtil.getInt(PreferencesUtil.LOGIN_TYPE, -1) == 2) {
            UMShareAPI.get(this).deleteOauth(this, SHARE_MEDIA.WEIXIN, null);
        }
        PreferencesUtil.clear();
        startActivity(new Intent(this, LoginActivity.class));
        sendBroadcast(new Intent(BillionCardConstants.MSG_LOG_OUT));
        finish();
    }

    //弹窗（选择支付方式）
    private void setPayDialog() {
        new BottomDialog(this).addItemSheet(R.string.alipay, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                commitApply("ali");
            }
        }).addItemSheet(R.string.wechat, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                ToastUtil.showToast(ApplyShopActivity.this, "暂未开通微信支付");
//                commitApply("wx");
            }
        }).setCancel(new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
            }
        }).show();
    }

    //订单支付
    private void commitApply(final String payWay) {
        NetworkManager.commitApply(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), payWay, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                ToastUtil.logResult("支付接口", result);
                String orderInfo = null;
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    orderInfo = jsonObject.getString("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (payWay.equals("wx")) {//微信支付

                }
                if (payWay.equals("ali")) {//支付宝支付
                    toAliPay(orderInfo);
                }
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                ToastUtil.logError("支付接口错误===", errorCode, errorDiscription);
            }
        });
    }

    /**
     * 支付(支付宝)
     */
    private void toAliPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ApplyShopActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus，为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        ToastUtil.showToast(ApplyShopActivity.this, "支付成功");
//                        ApplyShopActivity.this.finish();
                        getApplyOpenShop();//调取接口上传数据申请开店
                    } else {
                        //该笔订单真实的支付结果，需要依赖服务端的异步通知
                        ToastUtil.showToast(ApplyShopActivity.this, "支付失败");
//                        ApplyShopActivity.this.finish();
                    }
            }
        }
    };


    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(ApplyShopActivity.this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(ApplyShopActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(ApplyShopActivity.this,
                    new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, 123);

        }
    }

    /**
     * 权限获取回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 123: {
                // 用户取消了权限弹窗
                if (grantResults.length == 0) {
                    return;
                }
                // 用户拒绝了某些权限
                for (int x : grantResults) {
                    if (x == PackageManager.PERMISSION_DENIED) {
                        return;
                    }
                }
                // 所需的权限均正常获取
            }
        }
    }
}
